import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import App from './App.vue'

// Capacitor imports
import { Capacitor } from '@capacitor/core'
import { StatusBar, Style } from '@capacitor/status-bar'
import { SplashScreen } from '@capacitor/splash-screen'
import { Keyboard } from '@capacitor/keyboard'
import { App as CapApp } from '@capacitor/app'

// 导入浏览器兼容性工具
import { 
  setupGlobalErrorHandling, 
  showCompatibilityWarning, 
  checkCriticalFeatures,
  handleCompatibilityError 
} from './utils/browserCompatibility'

// 导入登录页面检测工具
import { initLoginPageDetection } from './utils/loginPageDetector'

// 导入企业微信工具
import { isWeChatWork, getWeChatJsApiConfig } from './utils/wechat'

// 导入Bootstrap CSS和JS
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.bundle.min.js'

// 导入Bootstrap Icons
import 'bootstrap-icons/font/bootstrap-icons.css'

// 导入自定义样式
import './styles/main.css'
import './styles/mobile.css'
import './assets/css/responsive.css'

// Capacitor平台初始化
const initializeCapacitor = async () => {
  if (Capacitor.isNativePlatform()) {
    console.log('运行在原生平台:', Capacitor.getPlatform())
    
    try {
      // 设置状态栏样式
      await StatusBar.setStyle({ style: Style.Dark })
      await StatusBar.setBackgroundColor({ color: '#667eea' })
      
      // 隐藏启动屏幕
      await SplashScreen.hide()
      
      // 键盘配置
      Keyboard.addListener('keyboardWillShow', () => {
        document.body.classList.add('keyboard-open')
      })
      
      Keyboard.addListener('keyboardWillHide', () => {
        document.body.classList.remove('keyboard-open')
      })
      
      // 应用状态监听
      CapApp.addListener('appStateChange', ({ isActive }) => {
        console.log('应用状态变化:', isActive ? '激活' : '后台')
      })
      
      // 返回按钮处理
      CapApp.addListener('backButton', ({ canGoBack }) => {
        if (!canGoBack) {
          CapApp.exitApp()
        } else {
          window.history.back()
        }
      })
      
    } catch (error) {
      console.error('Capacitor初始化错误:', error)
    }
  } else {
    console.log('运行在Web平台')
  }
}

// 设置全局错误处理
setupGlobalErrorHandling()

// 检查关键功能（仅在Web平台）
if (!Capacitor.isNativePlatform() && !checkCriticalFeatures()) {
  console.error('浏览器缺少关键功能，可能无法正常运行')
}

// 显示兼容性警告（仅在Web平台）
if (!Capacitor.isNativePlatform()) {
  showCompatibilityWarning()
}

// 企业微信环境初始化
const initializeWeChatWork = async () => {
  if (isWeChatWork()) {
    console.log('检测到企业微信环境，正在初始化...')
    
    try {
      // 获取JS-SDK配置
      const config = await getWeChatJsApiConfig(window.location.href)
      
      // 配置企业微信JS-SDK
      if (typeof wx !== 'undefined') {
        wx.config({
          beta: true,
          debug: false,
          appId: config.appId,
          timestamp: config.timestamp,
          nonceStr: config.nonceStr,
          signature: config.signature,
          jsApiList: [
            'getContext',
            'selectEnterpriseContact',
            'openEnterpriseChat',
            'shareToExternalContact',
            'makePhoneCall',
            'showLoading',
            'hideLoading',
            'showToast',
            'showModal',
            'setNavigationBarTitle',
            'setNavigationBarColor'
          ]
        })
        
        console.log('企业微信JS-SDK配置完成')
      }
    } catch (error) {
      console.error('企业微信初始化失败:', error)
    }
  } else {
    console.log('非企业微信环境')
  }
}

// 初始化登录页面检测
initLoginPageDetection()

// 创建应用实例
const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(router)

// 添加错误处理
app.config.errorHandler = (err, instance, info) => {
  console.error('Vue应用错误:', err, info)
  handleCompatibilityError(err, () => {
    // 重试逻辑：重新挂载应用
    app.mount('#app')
  })
}

// 初始化应用
const initApp = async () => {
  try {
    // 初始化Capacitor
    await initializeCapacitor()
    
    // 初始化企业微信环境
    await initializeWeChatWork()
    
    // 挂载应用
    app.mount('#app')
    
    console.log('应用初始化完成')
  } catch (error) {
    console.error('应用初始化失败:', error)
    handleCompatibilityError(error, () => {
      // 延迟重试
      setTimeout(() => {
        app.mount('#app')
      }, 2000)
    })
  }
}

// 启动应用
initApp()